package com.abigdreamer.net.p2p;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.List;

public class FileTransProc extends AUpdSrvProc {

	private File transFile;
	private FileProcessListener listener;

	public FileTransProc(Socket socket, File transFile, FileProcessListener listener) {
		super(socket);

		this.listener = listener;

		this.transFile = transFile;

		registeCmd(AUPD.READY_TO_UPDATE, "readyToUpdate");// 客户端已经准备好更新了
	}

	public String readyToUpdate() {
		Config.print(socket.getInetAddress() + ":客户端已经准备好接收更新文件");
		return sendFile(transFile);
	}

	private void bye() throws IOException {
		socketOut.write(Config.packingCmd(AUPD.BYE));
	}

	// false.失败 true.成功
	private String sendFile(File file) {
		try {
			Config.print(socket.getInetAddress() + ":开始传输文件>>" + file);

			socketOut.write(Config.packingCmd(AUPD.START_TRANSMIT));// 开始传输

			List<byte[]> packedData = FileContract.packing(file, socketOut, listener);
			if(packedData != null) {
				int totalPackCount = packedData.size();
				int currentPackIndex = 0;
				for (byte[] bs : packedData) {
					socketOut.write(bs);
					listener.onProcess(++currentPackIndex, totalPackCount);
				}
				socketOut.flush();
			}

			String cmd = FileContract.unpackingCmd(socketIn);
			if (cmd == null) {
				Config.print(socket.getInetAddress() + ":读取命令失败,CMD=" + cmd);
				bye();// 结束
				return AUPD.UPDATED_FAILURE;
			}

			if (cmd.equals(AUPD.TERMINATE_TRANSMIT)) {// 成功
				Config.print(socket.getInetAddress() + ":传输文件'" + file + "'成功");
				return AUPD.UPDATED_SUCCESSFUL;
			} else if (cmd.equals(AUPD.BYE)) {// 失败
				Config.print(socket.getInetAddress() + ":传输文件失败，" + file);
				return AUPD.UPDATED_FAILURE;
			} else {// 异常
				Config.print(socket.getInetAddress() + ":传输文件异常，" + file + "," + cmd);
				return AUPD.UPDATED_FAILURE;
			}
		} catch (Exception e) {
			Config.print("传输文件'" + file + "'失败," + e);
			e.printStackTrace();
			return AUPD.UPDATED_FAILURE;
		}
	}

	public static void main(String[] args) {

		double totalPackCount = 7;
		int currentPackIndex = 0;
		for (int i = 0; i < totalPackCount; i++) {
			Double currentPrecent = ++currentPackIndex / totalPackCount * 100;

			System.out.println(currentPrecent.intValue());
		}

	}
}
